package com.redstar.HappyRefresh.audit;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.redstar.HappyRefresh.response.AuditResponse;
import com.redstar.HappyRefresh.config.QiNiuConfig;
import com.redstar.HappyRefresh.constant.AuditMsgMap;
import com.redstar.HappyRefresh.constant.AuditStatus;
import com.redstar.HappyRefresh.json.*;
import com.redstar.HappyRefresh.pojo.Setting;
import com.redstar.HappyRefresh.service.SettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.UUID;

@Service
public abstract class AbstractAuditService<T, R> implements AuditService<T, R> { // 统一封装审核逻辑,用于给子类进行编排或者调用普通逻辑

    @Autowired
    protected QiNiuConfig qiNiuConfig; // 七牛云配置
    @Autowired
    protected SettingService settingService; // 设置服务
    // 在反序列化过程中，当遇到未知属性时不会导致失败
    protected ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    public static final String contentType = "application/json";

    protected AuditResponse audit(ScoreJson scoreJson, BodyJson bodyJson) { // 审核
        // 封装视频审核返回的结果
        AuditResponse audit = new AuditResponse();
        // scoreJson是需要人工审核的审核规则，所有截帧的置信度都小于scoreJson中的最小值代表审核通过，存在大于scoreJson中的最大值代表审核失败
        audit = auditNext(scoreJson, bodyJson);
        if (audit.getFlag()) { // 审核未通过
            return audit;
        }
        // 置信度审核通过后比较七牛云给出的审核建议
        ScenesJson scenes = bodyJson.getResult().getResult().getScenes();
        if (endCheck(scenes)) {
            audit.setAuditStatus(AuditStatus.SUCCESS);
            audit.setMsg("正常");
        } else { // 前面已经通过了置信度比较，最后审核未通过转入人工审核
            audit.setAuditStatus(AuditStatus.MANUAL);
            audit.setMsg("内容不合法");
        }
        return audit;
    }

    private AuditResponse auditNext(ScoreJson scoreJson, BodyJson bodyJson) { // 判断是否命中当前的审核标准，scoreJson 系统设置的审核标准，bodyJson 七牛云返回的审核结果
        AuditResponse auditResponse = new AuditResponse();
        auditResponse.setFlag(true);
        // 政治
        Double minPolitician = scoreJson.getMinPolitician();
        Double maxPolitician = scoreJson.getMaxPolitician();
        List<CutsJson> politician = bodyJson.getPolitician(); // 关于政治方面的审核信息
        if (!ObjectUtils.isEmpty(politician)) {
            if (bodyJson.checkViolation(politician, minPolitician)) { // 判断是否存在截帧不符合审核通过的标准
                AuditResponse aResponse = getInfo(politician, maxPolitician, maxPolitician, "group");
                auditResponse.setMsg(aResponse.getMsg());
                auditResponse.setOffset(aResponse.getOffset());
               if (aResponse.getFlag()) { // 审核失败
                   auditResponse.setAuditStatus(AuditStatus.PASS);
               } else { // 人工审核
                   auditResponse.setAuditStatus(AuditStatus.MANUAL);
               }
                return auditResponse;
            }
        }
        // 色情
        Double minPulp = scoreJson.getMinPulp();
        Double maxPulp = scoreJson.getMaxPulp();
        List<CutsJson> pulp = bodyJson.getPulp(); // 关于色情方面的审核信息
        if (!ObjectUtils.isEmpty(pulp)) {
            if (bodyJson.checkViolation(pulp, minPulp)) { // 判断是否存在截帧不符合审核通过的标准
                AuditResponse aResponse = getInfo(politician, maxPolitician, maxPolitician, "normal");
                auditResponse.setMsg(aResponse.getMsg());
                auditResponse.setOffset(aResponse.getOffset());
                if (aResponse.getFlag()) { // 审核失败
                    auditResponse.setAuditStatus(AuditStatus.PASS);
                } else { // 人工审核
                    auditResponse.setAuditStatus(AuditStatus.MANUAL);
                }
                return auditResponse;
            }
        }
        // 暴恐
        Double minTerror = scoreJson.getMinTerror();
        Double maxTerror = scoreJson.getMaxTerror();
        List<CutsJson> terror = bodyJson.getTerror(); // 关于暴恐方面的审核信息
        if (!ObjectUtils.isEmpty(terror)) {
            if (bodyJson.checkViolation(terror, minTerror)) { // 判断是否存在截帧不符合审核通过的标准
                AuditResponse aResponse = getInfo(terror, minTerror, maxTerror, "normal");
                auditResponse.setMsg(aResponse.getMsg());
                auditResponse.setOffset(aResponse.getOffset());
                if (aResponse.getFlag()) { // 审核失败
                    auditResponse.setAuditStatus(AuditStatus.PASS);
                } else { // 人工审核
                    auditResponse.setAuditStatus(AuditStatus.MANUAL);
                }
                return auditResponse;
            }
        }
        // 标记为审核通过
        auditResponse.setFlag(false);
        return auditResponse;
    }

    private boolean endCheck(ScenesJson scenes) { // 最后检查审核建议
        TypeJson terror = scenes.getTerror();
        TypeJson politician = scenes.getPolitician();
        TypeJson pulp = scenes.getPulp();
        return terror.getSuggestion().equals("pass") && politician.getSuggestion().equals("pass") && pulp.getSuggestion().equals("pass");
    }

    private AuditResponse getInfo(List<CutsJson> type, Double min, Double max, String key) { // 存在截帧命中当前的审核标准
        AuditResponse auditResponse = new AuditResponse();
        for (CutsJson t : type) {
            for (DetailsJson detail : t.getDetails()) {
                Double score = detail.getScore();
                if (score >= min) { // 审核未通过
                    if (!detail.getLabel().equals(key)) {
                        String info = AuditMsgMap.getInfo(detail.getLabel());
                        auditResponse.setMsg(info);
                    }
                    auditResponse.setOffset(t.getOffset());
                }
                if (score > max) { // 审核失败
                    if (ObjectUtils.isEmpty(auditResponse.getMsg())) {
                        auditResponse.setMsg("该视频违法乐刷平台规则");
                    }
                    auditResponse.setFlag(true);
                    return auditResponse;
                }
            }
        }
        // 人工审核
        auditResponse.setFlag(false);
        if (ObjectUtils.isEmpty(auditResponse.getMsg())) {
            auditResponse.setMsg("该视频违法乐刷平台规则");
        }
        return auditResponse;
    }

    protected Boolean isNeedAudit() { // 根据系统配置表查询是否需要审核
        Setting setting = settingService.list().get(0);
        // 返回审核开关
        return setting.getAuditOpen();
    }

    protected String appendUUID(String url) { // 为url追加uuid字符串，拼接在url后面，并记录在本地缓存LocalCache中
        Setting setting = settingService.list().get(0);
        if (setting.getAuth()) {
            String uuid = UUID.randomUUID().toString();
            if (url.contains("?")) {
                url = url + "&uuid=" + uuid;
            } else {
                url = url + "?uuid=" + uuid;
            }
            return url;
        }
        return url;
    }
}
